package cn.zcy.handler.impl;

import cn.zcy.handler.ResultSetHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class BeanListHandler<T> implements ResultSetHandler {

    //定义分装到那个类的字节码
    private Class<T> requiredType;

    public BeanListHandler(Class requiredType) {
        this.requiredType = requiredType;
    }

    /**
     * @param resultSet
     * @return
     */
    @Override
    public Object handle(ResultSet resultSet) {
        //定义返回值
        List<T> list = new ArrayList<>();
        T bean = null;
        try {
            //遍历是否有结果结
            while (resultSet.next()) {
                //实例化返回对象 ,反射
                bean = requiredType.newInstance();
                //获取结果集的源信息
                ResultSetMetaData metaData = resultSet.getMetaData();
                //获取结果集的列数
                int columnCount = metaData.getColumnCount();
                for (int i = 0; i < columnCount; i++) {
                    //取出列的标题
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    //取出数据内容
                    Object value = resultSet.getObject(columnLabel);
                    //借助java的内省机制，属性填充器
                    PropertyDescriptor pd = new PropertyDescriptor(columnLabel, requiredType);
                    //获取写方法
                    Method method = pd.getWriteMethod();
                    //执行方法
                    method.invoke(bean, value);
                    //把填充好的bean分装到集合集合中
                    list.add(bean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }
}
